<template>
    <div class="detail_module_panel personal_info">
        <h3 id="personal_info" class="detail_panel_title detail_panel_title_icon personal_info_icon">
            {{$t('common.personalInfo')}}
            <el-button type="primary" @click="beforeUnFreezeHandler" :disabled="!userId || isDisabledUnfreeze || !canUnFreezeHandler" style="margin-left:20px;">
                <span v-if="canUnFreezeHandler">{{$t('audit.unFreeze')}}{{'(' + remainDays + $t('common.day') + ')'}}</span>
                <span v-else>{{$t('audit.unFreeze')}}</span>
            </el-button>
        </h3>
        <div class="panel_info_content">
            <el-row class="row">
                <el-col class="label" :span="4">{{$t('common.name')}}</el-col><!--姓名-->
                <el-col class="info" :span="20">
                    {{ userData.realName }}
                    <el-button v-if="orderId && isNeedReverse === 'true'" type="primary" size="mini" @click="changeName" >{{ $t('operation.modify') }}</el-button>
                </el-col>
            </el-row>
            <el-row class="row">
                <el-col class="label" :span="4">{{$t('common.gender')}}</el-col><!--性别-->
                <el-col class="info" :span="20">{{ userData.sex | switchSex }}
                </el-col>
            </el-row>
            <el-row class="row">
                <el-col class="label" :span="4">{{$t('common.dateOfBirth')}}</el-col><!--出生日期-->
                <el-col class="info" :span="20">{{ userData.birthDay | formatDate('yyyy-MM-dd') }}
                </el-col>
            </el-row>
            <el-row class="row">
                <el-col class="label" :span="4">{{$t('common.mobileNumber')}}</el-col><!--手机号码-->
                <el-col class="info" :span="20"><button @click="call(userData.userPhone)" class="btn-call" :disabled="!orderId || isCalling">{{ userData.userPhone }}</button></el-col>
                <!-- <el-col class="info" :span="20">{{ userData.userPhone }}<span>（{{ $t('common.addressBookMatch') }}：{{ userData.phoneList || $t('common.none') }}）</span></el-col> -->
            </el-row>
            <el-row class="row">
                <el-col class="label" :span="4">{{$t('common.address')}}</el-col><!--地址-->
                <el-col class="info" :span="20">{{ address }}</el-col>
            </el-row>
            <el-row class="row">
                <el-col class="label" :span="4">{{$t('common.education')}}</el-col><!--学历-->
                <el-col class="info" :span="20">{{ userData.education | switchEducation }}</el-col>
            </el-row>
            <el-row class="row">
                <el-col class="label" :span="4">{{$t('common.religion')}}</el-col><!--宗教-->
                <el-col class="info" :span="20">{{ userData.religion | switchReligion }}</el-col>
            </el-row>
            <el-row class="row">
                <el-col class="label" :span="4">{{$t('common.isMarried')}}</el-col><!--婚姻状况-->
                <el-col class="info" :span="20">{{ userData.civilStatus | switchCivilStatus }}</el-col>
            </el-row>

            <el-row class="row">
                <el-col class="label" :span="4">{{$t('common.numberOfChildren')}}</el-col><!--子女个数-->
                <el-col class="info" :span="20">{{ userData.childrenNumber | switchChild }}</el-col>
            </el-row>

            <!--<el-row class="row">-->
                <!--<el-col class="label" :span="4">{{$t('common.monthlyIncome')}}</el-col>&lt;!&ndash;月收入&ndash;&gt;-->
                <!--<el-col class="info" :span="20">{{ userData.salary }}</el-col>-->
            <!--</el-row>-->
            <el-row class="row">
                <el-col class="label" :span="4">{{$t('common.email')}}</el-col><!--邮箱-->
                <el-col class="info" :span="20">{{ userData.email }}</el-col>
            </el-row>
            <el-row class="row">
                <el-col class="label" :span="4">{{$t('common.idCardType')}}</el-col><!--证件类型-->
                <el-col class="info" :span="20">{{ userData.identificationType }}</el-col>
            </el-row>
            <el-row class="row">
                <el-col class="label" :span="4">{{$t('common.idCardNumber')}}</el-col><!--证件号码-->
                <el-col class="info" :span="20">{{ userData.cardId }}</el-col>
            </el-row>
            <el-row class="row">
                <el-col class="label" :span="4">{{$t('common.backupPhone')}}</el-col><!--备用号码-->
                <el-col class="info" :span="20"><button @click="call(userData.phone)" class="btn-call" :disabled="!orderId || isCalling">{{ userData.phone }}</button></el-col>
            </el-row>
            <el-row class="row">
                <el-col class="label" :span="4">{{$t('common.socialAccount')}}</el-col><!--社交账号-->
                <el-col class="info" :span="20">{{ userData.socialAccountType }} - <button @click="call(userData.socialAccount)" class="btn-call" :disabled="!orderId || isCalling">{{ userData.socialAccount }}</button></el-col>
            </el-row>
            <el-row class="row">
                <el-col class="label" :span="4">{{$t('common.faceValidResult')}}</el-col><!--活体检测结果-->
                <el-col class="info" :span="20">{{userData.faceValid | switchFaceValid}}</el-col>
            </el-row>
            <el-row class="row" v-if="orderId && orderId !== 'null'">
                <el-col class="label" :span="4">{{$t('common.imgContrastUserId')}}</el-col><!--对比照片 userID-->
                <el-col class="info" :span="20">{{selectFaceSearch.first_user || '-'}}</el-col>
            </el-row>
            <el-row class="row" v-if="orderId && orderId !== 'null'">
                <el-col class="label" :span="4">{{$t('common.imgContrastPhone')}}</el-col><!--对比照片 手机号-->
                <el-col class="info" :span="20">{{selectFaceSearch.phone || '-'}}</el-col>
            </el-row>
            <el-row class="row" v-if="orderId && orderId !== 'null'">
                <el-col class="label" :span="4">{{$t('common.imgContrast')}}</el-col><!--照片对比度-->
                <el-col class="info" :span="20">{{selectFaceSearch.first_confidence | toPercent}}</el-col>
            </el-row>
            <el-row class="row">
                <el-col class="label" :span="4">{{$t('common.idInfoCollect')}}</el-col>
                <el-col class="info" :span="20">
                    <ul class="imgs">
                        <li>
                            <!--身份证正面-->
                            <a @click="showImg(userData.cardPositiveImg)" :style="backgroundImg(userData.cardPositiveImg)" href="javascript:void(0);"></a>
                            <span class="img_desc">{{$t('common.idCardFrontSide')}}</span>
                        </li>
                        <li>
                            <!--手持身份证照片-->
                            <a @click="showImg(userData.cardImg)" :style="backgroundImg(userData.cardImg)" href="javascript:void(0);"></a>
                            <span class="img_desc">{{$t('common.handCardPic')}}</span>
                        </li>
                        <li>
                            <!--活体照片-->
                            <a @click="showImg(userData.faceValidImg)" :style="backgroundImg(userData.faceValidImg)" href="javascript:void(0);"></a>
                            <span class="img_desc">{{$t('common.faceValidImg')}}</span>
                        </li>
                        <!--<li v-if="orderId && orderId !== 'null'">
                            &lt;!&ndash;匹配照片&ndash;&gt;
                            <a @click="showImg(selectFaceSearch.first_images_url)" :style="backgroundImg(selectFaceSearch.first_images_url)" href="javascript:void(0);"></a>
                            <span class="img_desc">{{$t('common.matchPhoto')}}</span>
                        </li>-->
                        <li v-if="orderId && orderId !== 'null' && overdueFaceInfo.first_images_url" class="overdue_face">
                            <!--逾期人脸照片-->
                            <a @click="showImg(overdueFaceInfo.first_images_url)" :style="backgroundImg(overdueFaceInfo.first_images_url)" href="javascript:void(0);"></a>
                            <span class="img_desc">{{$t('common.overdueFacePhoto')}}</span>
                        </li>
                        <li>
                            <!--Front of ID-->
                            <a @click="showImg(userData.frontOfIdImg)" :style="backgroundImg(userData.frontOfIdImg)" href="javascript:void(0);"></a>
                            <span class="img_desc">{{ $t('common.idCardFrontSideAdd')}}</span>
                        </li>
                    </ul>
                </el-col>
            </el-row>
        </div>
        <show-image-video :visible.sync="showImgDialog" :img-src="imgUrl">图片展示</show-image-video>

        <!--修改姓名弹框-->
        <el-dialog :visible.sync="changeNameDialog.isVisible" width="400px" :title="$t('operation.modify')" class="changeNameDialog" :close-on-click-modal="false">
            <div class="name">{{$t('common.name')}}:{{ changeNameDialog.form.lastName }} {{ changeNameDialog.form.firstName }} {{ changeNameDialog.form.middleName }}</div>
            <el-form :model="changeNameDialog.form" ref="editForm" :rules="changeNameDialog.rules" :inline="false">
                <el-form-item prop="lastName" label="Last Name">
                    <el-input v-model="changeNameDialog.form.lastName" type="text" maxlength="50"></el-input>
                </el-form-item>
                <el-form-item prop="firstName" label="First Name">
                    <el-input v-model="changeNameDialog.form.firstName" type="text" maxlength="50"></el-input>
                </el-form-item>
                <el-form-item prop="middleName" label="Middle Name">
                    <el-input v-model="changeNameDialog.form.middleName" type="text" maxlength="50"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="changeNameSubmit">{{$t('common.submit')}}</el-button>
                <el-button type="default" @click="changeNameDialog.isVisible = false">{{$t('common.cancel')}}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import ShowImageVideo from '@/components/show-image-video';

    let that = null;
    export default {
        name: 'personalInfo',
        props: {
            userData: {
                type: Object
            },
            isCalling: {
                type: Boolean
            }
        },
        components: {
            ShowImageVideo
        },
        data() {
            return {
                userId: '',
                orderId: '',
                isNeedReverse: '',
                canUnFreezeHandler: false,//解冻开关
                remainDays: '', // 拒绝天数
                aduitLoan: {
                    inputId: '',
                    ocrId: '',
                },
                ruleForm: {
                    checkIdCardNumber: '',
                },
                checkIdCardNumberList: [{id: 123, status: 0}, {id: 456, status: 1}],
                rules: {
                    checkIdCardNumber: [
                        {required: true, message: this.$t('verify.plsInput'), trigger: 'blur'}
                    ],
                },
                isDisabledUnfreeze: false,
                showImgDialog: false,
                imgUrl: '',
                selectFaceSearch: {
                    first_images_url: '',
                    first_confidence: '',
                    first_user: '',
                    phone: ''
                },
                changeNameDialog: {
                    isVisible: false,
                    form: {
                        lastName: '',
                        firstName: '',
                        middleName: '',
                    },
                    rules: {
                        lastName: [
                            {required: true, message: this.$t('verify.plsInput'), trigger: 'blur'},
                            {pattern: /^[^0-9]+$/, message: this.$t('verify.plsInputRightX',{x: 'last name'})},
                        ],
                        firstName: [
                            {required: true, message: this.$t('verify.plsInput'), trigger: 'blur'},
                            {pattern: /^[^0-9]+$/, message: this.$t('verify.plsInputRightX',{x: 'first name'})},
                        ],
                        middleName: [
                            // {required: true, message: this.$t('verify.plsInput'), trigger: 'blur'},
                            {pattern: /^[^0-9]+$/, message: this.$t('verify.plsInputRightX',{x: 'middle name'})},
                        ],
                    }
                },
                overdueFaceInfo: {
                    first_images_url: '',
                    first_confidence: '',
                },
            };
        },
        computed: {
            address() {
                let address = '';
                const baseInfo = this.userData;
                if (baseInfo.address) {
                    address = baseInfo.district + ' ' + baseInfo.province + ' ' + baseInfo.townCity + ' ' + baseInfo.address;
                }
                return address;
            },
        },
        methods: {
            beforeUnFreezeHandler() {
                this.$confirm(this.$tc('common.confirmUnFreeze'), '', {
                    confirmButtonText: this.$t('common.confirm'),
                    cancelButtonText: this.$t('common.cancel'),
                    type: 'warning'
                }).then(() => {
                    this.unFreezeHandler();
                }).catch(() => {

                });
            },
            unFreezeHandler() {
                const params = {
                    userId: this.userId,
                    orderId:this.orderId
                };
                this.isDisabledUnfreeze = true;
                this.$api.audit.updateUserLoanStatus(params).then((res) => {
                    this.isDisabledUnfreeze = false;
                    const {status, error, msg} = res;
                    if ('1' === status && error === '00000000') {
                        this.$message.success(this.$tc('common.successfulOperation'));
                        this.isCanUnfreeze();
                    }
                    else {
                        this.$message.error(msg);
                    }
                });
            },
            backgroundImg(url) {
                // 构造图片展示
                const style = {};
                if (url) {
                    style.backgroundImage = 'url("' + url + '")';
                }
                return style;
            },
            showImg(url, video) {
                if (video && url) {
                    this.videoUrl = url;
                    // this.videoUrl = 'http://www.w3school.com.cn/i/movie.ogg';
                    this.imgUrl = '';
                    this.showImgDialog = true;
                } else if (!video && url) {
                    this.showImgDialog = true;
                    this.imgUrl = url;
                    this.videoUrl = '';
                }
            },
            selectFaceSearchM() {
                const params = {
                    userId: this.userId,
                    orderId: this.$route.params.orderId || 0,
                };
                this.$api.signSource.selectFaceSearch(params).then((res) => {
                    const { status, data, error } = res;
                    // 匹配照片对比对低于0.9的不显示相关信息
                    if ('1' === status && '00000000' === error && data && (+data.first_confidence >= 0.95)) {
                        this.selectFaceSearch.first_images_url = data.first_images_url || '';
                        this.selectFaceSearch.first_confidence = data.first_confidence || '';
                        this.selectFaceSearch.first_user = data.first_user || '';
                        this.findUserById(this.selectFaceSearch.first_user);
                    }
                });
            },
            findUserById(id) {
                const params = {
                    id: id
                };
                this.$api.customer.findUserById(params).then((res) => {
                const { status, data, error } = res;
                    if ('1' === status && '00000000' === error && data) {
                        this.selectFaceSearch.phone = data.phone;
                    }
                });
            },
            //根据订单获取拒绝天数
            isCanUnfreeze() {
                const params = {
                    userId: this.userId,
                    orderId:''
                };
                if(this.orderId){
                    params.orderId = this.orderId
                }
                this.$api.audit.isCanUnfreeze(params).then((res) => {
                const { status, data, error } = res;
                    if ('1' === status && '00000000' === error && data) {
                        if (+data.mark === 0) {
                            this.canUnFreezeHandler = true;
                            this.remainDays = data.remainDays;
                            this.orderId = data.orderId;
                        }else if (+data.mark === 1) {
                            this.canUnFreezeHandler = false;
                        }
                    }
                });
            },
            call(number) {
                this.$emit('call',number);
            },
            changeName() {
                let form = this.changeNameDialog.form;
                form.lastName = this.userData.lastName;
                form.firstName = this.userData.firstName;
                form.middleName = this.userData.middleName;
                this.changeNameDialog.isVisible = true;
            },
            changeNameSubmit() {
                const editForm = this.$refs.editForm;
                editForm.validate(val => {

                    if (val) {
                        const form = this.changeNameDialog.form;
                        Object.keys(form).forEach(key => {
                            if (typeof form[key] === 'string') {
                                form[key] = form[key].trim();
                            }
                        });
                        const {lastName, firstName, middleName} = this.changeNameDialog.form;
                        const params = {
                            lastName,
                            firstName,
                            middleName,
                            realName: lastName + ' ' + firstName + (middleName ? ' ' + middleName : ''),
                            userId: this.userId,
                            orderId: this.orderId
                        };
                        this.$api.customer.editUserName(params).then((res) => {
                            const { status, error } = res;
                            if ('1' === status && '00000000' === error) {
                                // this.userData.realName = lastName + ' ' + firstName + ' ' + middleName;
                                this.changeNameDialog.isVisible = false;
                                this.$message.success(this.$tc('common.successfulOperation'));
                                this.$emit('refresh', 'personalInfo');
                            }
                        });
                    }

                });
            },
            // 获取逾期人脸信息
            getOverdueFace() {
                const params = {
                    userId: this.userId,
                    orderId: this.$route.params.orderId || 0,
                };
                this.$api.signSource.selectFaceOverdueSearch(params).then((res) => {
                    const { status, data, error } = res;
                    // 匹配照片对比对低于0.9的不显示相关信息
                    // 信审后台1:N逾期人脸展示阈值从0.9调整到0.95 2021-05-31
                    if ('1' === status && '00000000' === error && data && (+data.first_confidence >= 0.95)) {
                        this.overdueFaceInfo.first_images_url = data.first_images_url || '';
                        this.overdueFaceInfo.first_confidence = data.first_confidence || '';
                    }
                });
            },
        },
        filters: {
            switchSex(type) {
                switch (type) {
                    case 'Male':
                        return that.$t('common.male');// 男
                    case 'Female':
                        return that.$t('common.female');// 女
                    default:
                        return type;
                }
            },
            switchEducation(type) {
                switch (type) {
                    case 'Untutored':
                        return that.$t('common.eductaion.Untutored');// 未受教育
                    case 'Primary':
                        return that.$t('common.eductaion.Primary');// 小学
                    case 'Secondary':
                        return that.$t('common.eductaion.Secondary');// 中学
                    case 'Senior High School':
                        return that.$t('common.eductaion.SeniorHighSchool');// 高中
                    case "Vocational College":
                        return that.$t('common.eductaion.VocationalCollege');// 高职专科
                    case "University/College - Bachelor":
                        return that.$t('common.eductaion.Bachelor');// 大学/学院-本科
                    case 'University/College - Master':
                        return that.$t('common.eductaion.Master');// 大学/学院-硕士
                    case 'University - Doctor':
                        return that.$t('common.eductaion.Doctor');// 大学—博士
                    default:
                        return type;
                }
            },
            switchChild(type) {
                switch (type) {
                    case 3:
                        return that.$t('common.moreThanThree');// 3个及以上
                    default:
                        return type;
                }
            },
            switchCivilStatus(type) {
                switch (type) {
                    case 'UNMARRIED':
                        return that.$t('common.maritalStatus.UNMARRIED');// 未婚
                    case 'MARRIED ALREADY':
                        return that.$t('common.maritalStatus.MARRIEDALREADY');// 已婚已育
                    case 'MARRIED AND CHILDLESS':
                        return that.$t('common.maritalStatus.MARRIEDANDCHILDLESS');// 已婚未育
                    case 'WIDOW':
                        return that.$t('common.maritalStatus.WIDOW');// 丧偶（丧父）
                    case 'WIDOWER':
                        return that.$t('common.maritalStatus.WIDOWER');// 丧偶（丧妻）
                    case 'LEGAL SEPERATION':
                        return that.$t('common.maritalStatus.LEGALSEPERATION');// 离婚（不可再婚）
                    case 'GRANTED ANNULMENT':
                        return that.$t('common.maritalStatus.GRANTEDANNULMENT');// 离婚（可再婚）
                    default:
                        return type;
                }
            },
            switchReligion(type) {
                switch (type) {
                    case 'Christian':
                        return that.$t('common.religionData.Christian');// 基督教
                    case 'Catholic':
                        return that.$t('common.religionData.Catholic');// 天主教
                    case 'Islam/Muslim':
                        return that.$t('common.religionData.IslamMuslim');// 穆斯林
                    case 'Iglesia ni Cristo':
                        return that.$t('common.religionData.Iglesia');// 基督堂教会
                    case 'Buddhism':
                        return that.$t('common.religionData.Buddhism');// 佛教
                    case 'Others':
                        return that.$t('common.religionData.Others');// 其他
                    default:
                        return type;
                }
            },
            switchFaceValid(result) {
                switch (result + '') {
                    case '0':
                        return that.$t('common.pendingVerification');// 待验证
                    case '1':
                        return that.$t('common.success');// 成功
                    case '2':
                        return that.$t('common.fail');// 失败
                    default:
                        return result;
                }
            },
            toPercent(point){
                if (!point) {
                    return '-';
                }
                var str = Number(point * 100).toFixed(2);
                str += "%";
                return str;
            }
        },
        created() {
            that = this;
            if (this.$route.params.id) {
                this.userId = this.$route.params.id;
                this.orderId = this.$route.params.orderId;
                this.isNeedReverse = this.$route.params.isNeedReverse;
                this.isCanUnfreeze();
                this.selectFaceSearchM();
                this.getOverdueFace();
            }
        }
    };
</script>

<style lang="scss" scoped>
    .changeNameDialog {
        .name {
            margin:0 0 20px 0;
        }
    }
    .overdue_face{
        border: 1px solid red!important;
    }
</style>
